import Taro, { Component, Config } from '@tarojs/taro'
import { View, Input, Image, ScrollView } from '@tarojs/components'
import { SDBody, SDPopup } from 'sudao-ui'

import { DISCOVER_SEARCH_KEY } from '../../../redux/constants'

import SearchIcon from '../../../images/ic_search_black.png'
import PullDownIcon from '../../../images/ic_pulldown_nor.png'
import ClearIcon from '../../../images/ic_delete.png'

import './index.less'
import SDUtils from "sudao-utils";

type IPageState = {
  mainIsLoading: boolean,
  placeholder: string,
  classifyList: any[],
  currentClassify: any,
  hotKeywords: any[],
  searchHistory: any[]
}

export default class DiscoverSearchPage extends Component<{}, IPageState> {

  constructor () {
    super()
    this.state = {
      mainIsLoading: true,
      placeholder: '',
      classifyList: [],
      hotKeywords: [],
      searchHistory: [],
      currentClassify: {}
    }
  }

  config: Config = {
    navigationBarTitleText: '搜索',
    backgroundColor: '#fff'
  }

  componentDidMount () {
    // 当前groupCode
    this.code = (this.$router.params || {}).code || ''
    this.fetchData()
  }

  keywords: string = ''
  code: string = ''

  render () {
    const { mainIsLoading, searchHistory, hotKeywords, placeholder, classifyList, currentClassify } = this.state
    return (
      <SDBody sd-class='container' loading={mainIsLoading}>
        <View className="section-top">
          <View className="search-content">
            <View className="search-left">
              <Image className="search-icon" src={SearchIcon}></Image>
              <Input className="search-input" placeholder={placeholder} placeholderStyle='color: #999;' confirmType='search' onInput={this.onInputValueChange} onConfirm={this.onSearch}/>
            </View>
            <View className="search-btn" onClick={this.goBack}>取消</View>
          </View>
          <View className="picker-content" onClick={this.showPickerPopup}>
            <View className="picker-title">搜索类型：</View>
            <View className="picker-tips">{currentClassify.groupName}</View>
            <Image className="picker-icon" src={PullDownIcon}></Image>
          </View>
        </View>
        <View className="section-line"></View>

        <View className="main-content">
          {
            hotKeywords.length > 0 ? (
              <View className="section">
                <View className="section-header">
                  <View className="title">热门搜索</View>
                </View>
                <View className="section-list">
                  {
                    hotKeywords.map((item, index) => {
                      return (
                        <View className="cell-item" key={index} onClick={this.execSearch.bind(this, item, currentClassify.groupCode)}>
                          <View className="title">{item}</View>
                        </View>
                      )
                    })
                  }
                </View>
              </View>
            ) : null
          }

          {
            searchHistory.length > 0 ? (
              <View className="section">
                <View className="section-header">
                  <View className="title">搜索历史</View>
                  <View className="clear-btn" onClick={this.clearSearchHistory}>
                    <Image className="clear-icon" src={ClearIcon}></Image>
                  </View>
                </View>
                <View className="section-list">
                  {
                    searchHistory.map((item, index) => {
                      return (
                        <View key={index} className="cell-item" onClick={this.execSearch.bind(this, item, currentClassify.groupCode)}>
                          <View className="title">{item}</View>
                        </View>
                      )
                    })
                  }
                </View>
              </View>
            ) : null
          }
        </View>


        <SDPopup ref='pickerComps'>
          <View className="comps-picker-content">
            <View className="comps-picker_cell comps-picker-title border-bottom_1px">
              选择类型
            </View>
            <ScrollView className="comps-picker_scroll" scrollY>
              {
                classifyList.map((item, index) => {
                  return (
                    <View className={`comps-picker_cell comps-cell_item ${index == classifyList.length - 1 ? '' : 'border-bottom_1px'}`} key={index} onClick={this.onClassifyCellTaped.bind(this, index)}>
                      {item.groupName}
                    </View>
                  )
                })
              }
            </ScrollView>
            <View className="comps-picker_cell comps-picker_bottom border-top_1px" onClick={this.dismissPickerPopup}>
              取消
            </View>
          </View>
        </SDPopup>
      </SDBody>
    )
  }

  fetchData = async () => {
    let classifyList: any[] = []     // 分类
    let hotKeywords: any = []        // 热词
    let searchHistory: any = []      // 搜索历史
    let searchPlaceholder: string = ''
    let currentClassify = {}
    try {
      classifyList = await SDUtils.doGet('/content/wxmini/articleGroup/list?sortBy=group_code:asc')
      classifyList.unshift({
        groupCode: '',
        groupName: '全部',
        articleGroupId: 0
      })
      currentClassify = classifyList.find(item => item.groupCode == this.code)
      hotKeywords = ['品牌介绍', '怎样吸引客户', '如何快速提升销量', '迪士尼那些你不知道的品牌']
      searchHistory = Taro.getStorageSync(DISCOVER_SEARCH_KEY) || []
      searchPlaceholder = '手镯'
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      this.setState({
        mainIsLoading: false,
        classifyList: classifyList,
        hotKeywords: hotKeywords,
        placeholder: searchPlaceholder,
        searchHistory: searchHistory,
        currentClassify: currentClassify
      })
    }
  }

  showPickerPopup = () => {
    this.refs.pickerComps && this.refs.pickerComps.show()
  }

  dismissPickerPopup = () => {
    this.refs.pickerComps && this.refs.pickerComps.dismiss()
  }

  onClassifyCellTaped = (index: number) => {
    const { classifyList } = this.state
    this.setState({
      currentClassify: classifyList[index]
    })
    this.dismissPickerPopup()
  }

  goBack = () => {
    Taro.navigateBack()
  }

  onInputValueChange = e => {
    this.keywords = e.detail.value
  }

  onSearch = () => {
    const {currentClassify = {}} = this.state
    this.execSearch(this.keywords,currentClassify.groupCode || '' )
  }

  clearSearchHistory = () => {
    Taro.removeStorageSync(DISCOVER_SEARCH_KEY)
    this.setState({
      searchHistory: []
    })
  }

  execSearch = (keywords, code) => {
    let searchHistory = Taro.getStorageSync(DISCOVER_SEARCH_KEY) || []
    let idx = searchHistory.findIndex(item => item == keywords)
    if (idx >= 0) {
      searchHistory.splice(idx, 1)
    }
    searchHistory.unshift(keywords)
    searchHistory = searchHistory.slice(0, 10)
    Taro.setStorageSync(DISCOVER_SEARCH_KEY, searchHistory)
    console.log('DDDDDDD', code)
    SDUtils.jumpTo('../result/index', {keywords: keywords, code: code}, false)
  }
}
